package rs;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.wltea.expression.ExpressionEvaluator;
import org.wltea.expression.datameta.Variable;

import rs.util.StringUtil;

public class ModelFixer {
	public static ModelFixer instance = new ModelFixer();
	
	@SuppressWarnings("unchecked")
	public static Map<String, Object> fix(Map<String, Object> oriModel, String type){
		//专门针对含score和scoreFixer方法的处理
		Object sf = oriModel.get("scoreFixer");
		Object s = oriModel.get("score");
		if(sf != null && s != null){
			List<Variable> vars = new ArrayList<Variable>(2);
			vars.add(Variable.createVariable("score", s));
			vars.add(Variable.createVariable("x", s));
			Object result = ExpressionEvaluator.evaluate(sf.toString(), vars);
			oriModel.put("score", result);
		}
		//针对score处理结束
		
		Method method = null;
		try {
			method = ModelFixer.class.getDeclaredMethod(type, Map.class);
			return (Map<String, Object>)method.invoke(instance, oriModel);
		} catch (SecurityException e) {
			e.printStackTrace();
			return oriModel;
		} catch (NoSuchMethodException e) {
			//该type不需要fixer,或漏掉的fix方法,直接返回model
			return oriModel;
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			return oriModel;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return oriModel;
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			return oriModel;
		}
	}
	
	@SuppressWarnings("unused")
	private Map<String, Object> meituan(Map<String, Object> oriModel){
		String price = oriModel.get("price").toString();
		price = StringUtil.find(price, "\\d+");
		oriModel.put("price", price);
		
		String title = oriModel.get("title").toString();
		title = title.replaceFirst("<a.*?</a>", "");
		oriModel.put("title", title);
		return oriModel;
	}
	
	@SuppressWarnings("unused")
	private Map<String, Object> taobaoke(Map<String, Object> oriModel){
		String introduce = oriModel.get("introduce").toString();
		introduce = introduce.substring("var desc='".length(), introduce.length() - "';".length())
			.replaceAll("\\\\\\s", "");
		oriModel.put("introduce", introduce);
		
		oriModel.put("description", introduce);
		return oriModel;
	}
}
